﻿using AbpVnext_Module.Model;
using AbpVnext_Module.Repository;
using Microsoft.AspNetCore.Http;
using Microsoft.IdentityModel.JsonWebTokens;
using System.Security.Claims;
using Volo.Abp.Authorization.Permissions;

namespace AbpVnext_Module.Permission
{
    public class ProductPermissionValueProvider : PermissionValueProvider
    {
        public ProductPermissionValueProvider(IPermissionStore permissionStore) : base(permissionStore)
        {

        }
        public IPermissionGrantsRepository PermissionGrants { get; set; }

        public IHttpContextAccessor HttpContext { get; set; }

        public const string ProviderName = "Role";


        /// <summary>
        /// 基于角色鉴权
        /// </summary>
        public override string Name => "Role";

        /// <summary>
        /// 基于角色鉴权
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public override async Task<PermissionGrantResult> CheckAsync(PermissionValueCheckContext context)
        {
            //throw new NotImplementedException();
            if (HttpContext.HttpContext.User.Identity?.IsAuthenticated == false)
                return PermissionGrantResult.Undefined;
            //获取Cookie中的用户
            ClaimsPrincipal claimsPrincipal = context.Principal;
            //获取Product_Select权限
            Claim claim = claimsPrincipal.Claims.Where(x => x.Type == "Role").First();
            List<PermissionGrants> permissionGrants = await PermissionGrants.GetListAsync();
            var userList = permissionGrants.Where(x => x.ProviderName == Name && x.ProviderKey == claim.Value).ToList();
            //获取接口上的权限
            string PermissionName = context.Permission.Name;
            //if (PermissionName == "Product_Select_Page")
            //    return PermissionGrantResult.Granted;
            //鉴定用户是否有权限
            if (userList.Any(x => x.PermissionName == PermissionName))
            {
                //授予权限
                //return PermissionGrantResult.Prohibited;
                return PermissionGrantResult.Granted;
                //return PermissionGrantResult.Prohibited;
            }
            else
            {
                //鉴权失败
                return PermissionGrantResult.Undefined;
            }

            //return PermissionGrantResult.Undefined;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public override Task<MultiplePermissionGrantResult> CheckAsync(PermissionValuesCheckContext context)
        {
            throw new NotImplementedException();
        }
    }
}
